<route lang="json5">
{
  style: { navigationBarTitleText: 'Login' },
}
</route>
<template>
  <view class="login-container">
    <view class="logo-box">
      <image src="/static/logo.png" mode="aspectFit" class="logo" />
    </view>

    <wd-form ref="formRef" :model="formData" :rules="rules">
      <wd-form-item label="Username" prop="username">
        <wd-input v-model="formData.username" placeholder="Enter username" clearable />
      </wd-form-item>

      <wd-form-item label="Password" prop="password">
        <wd-input
          v-model="formData.password"
          type="password"
          placeholder="Enter password"
          clearable
        />
      </wd-form-item>

      <wd-form-item label="Verification Code" prop="validCode">
        <view class="captcha-container">
          <wd-input v-model="formData.validCode" placeholder="Enter verification code" />
          <image :src="captchaImage" @click="refreshCaptcha" class="captcha-image" />
        </view>
      </wd-form-item>

      <view class="options-row">
        <wd-checkbox v-model="formData.remember">Remember me</wd-checkbox>
      </view>

      <view class="submit-btn">
        <wd-button type="primary" block @click="handleLogin">Login</wd-button>
      </view>
    </wd-form>

    <view class="action-row">
      <text class="register-link" @click="goToRegister">New user? Register now</text>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useUserStore } from '@/store'
import { login, getPicCaptcha } from '@/service/user'
import { encryptPassword } from '@/utils/sm2'

const userStore = useUserStore()
const formRef = ref()
const captchaImage = ref('')
const validCodeReqNo = ref('')

const formData = reactive({
  username: '',
  password: '',
  remember: false,
  validCode: '',
})

const rules = {
  username: [
    { required: true, message: 'Please enter username' },
    { min: 3, message: 'Username must be at least 3 characters' },
  ],
  password: [
    { required: true, message: 'Please enter password' },
    { min: 6, message: 'Password must be at least 6 characters' },
  ],
  validCode: [{ required: true, message: 'Please enter verification code' }],
}

// 获取验证码
const refreshCaptcha = async () => {
  try {
    const res = await getPicCaptcha()
    captchaImage.value = res.data.validCodeBase64
    validCodeReqNo.value = res.data.validCodeReqNo
  } catch (error) {
    uni.showToast({
      title: 'Failed to get verification code',
      icon: 'none',
    })
  }
}

// 检查登录状态
const checkLoginStatus = () => {
  if (userStore.isLogined) {
    uni.showToast({
      title: 'Already logged in',
      icon: 'none',
    })
    setTimeout(() => {
      uni.switchTab({
        url: '/pages/index/index',
      })
    }, 1000)
  }
}

// 处理登录
const handleLogin = () => {
  formRef.value.validate().then(async () => {
    try {
      // 对密码进行 SM2 加密
      const encryptedPassword = encryptPassword(formData.password)

      const res = await login(
        formData.username,
        encryptedPassword, // 使用加密后的密码
        'PC',
        formData.validCode,
        validCodeReqNo.value,
      )
      if (res.code !== 200) {
        uni.showToast({
          title: res.msg,
          icon: 'none',
        })
        return
      }
      // 存储用户信息和token到store
      userStore.setUserInfo({
        token: res.data, // 直接存储返回的token字符串
        account: formData.username,
      })

      uni.showToast({
        title: 'Login successful',
        icon: 'success',
      })

      setTimeout(() => {
        uni.switchTab({
          url: '/pages/index/index',
        })
      }, 1500)
    } catch (error) {
      refreshCaptcha()
      uni.showToast({
        title: 'Login failed, please try again',
        icon: 'none',
      })
    }
  })
}

onMounted(() => {
  checkLoginStatus()
  refreshCaptcha()
})

const goToRegister = () => {
  uni.navigateTo({
    url: '/pages/my/register',
  })
}
</script>

<style lang="scss">
.login-container {
  padding: 40rpx;

  .logo-box {
    display: flex;
    justify-content: center;
    margin: 60rpx 0;

    .logo {
      width: 200rpx;
      height: 200rpx;
    }
  }

  .options-row {
    display: flex;
    align-items: center;
    margin: 20rpx 0;
  }

  .submit-btn {
    margin-top: 40rpx;
  }
}

.captcha-container {
  display: flex;
  gap: 20rpx;
  align-items: center;

  .captcha-image {
    width: 200rpx;
    height: 80rpx;
  }
}

.action-row {
  margin-top: 30rpx;
  text-align: center;

  .register-link {
    font-size: 28rpx;
    color: #0083ff;
  }
}
</style>
